/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } from "react";
import {
  Table,
  Input,
  Select,
  Button,
  Space,
  Row,
  Col,
  Pagination,
  Modal,
} from "antd";
import "./Client.scss";
import {
  PlusOutlined,
  DeleteOutlined,
  CopyOutlined,
  ExportOutlined,
  ImportOutlined,
  ReloadOutlined,
} from "@ant-design/icons";

const { Option } = Select;

// 导入ClientModal组件
import ClientModal from "./ClientModal";

// 客户数据类型定义
interface ClientData {
  key?: string;
  clientCode: string;
  clientName: string;
  industry: string;
  classification: string;
  contactPerson: string;
  contactPhone: string;
  email: string;
  department: string;
  responsiblePerson: string;
  status: string;
  address: string;
}

export default function Client() {
  // 状态管理
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentEditData, setCurrentEditData] = useState<
    ClientData | undefined
  >(undefined);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 模拟客户数据
  const generateClientData = (): ClientData[] => {
    const industries = [
      "零售",
      "制造",
      "医药",
      "工程",
      "食品",
      "商务",
      "代理商",
      "金融",
      "教育",
    ];
    const data: ClientData[] = [];

    for (let i = 1; i <= 100; i++) {
      data.push({
        key: i.toString(),
        clientCode: `KHDH${4345 + i}`,
        clientName: `客户${i}`,
        industry: industries[(i - 1) % industries.length],
        classification: "批发客户",
        contactPerson: "张三",
        contactPhone: "13808998543",
        email: "zs@example.com",
        department: "销售一部",
        responsiblePerson: "李四",
        status: "启用",
        address: "北京市朝阳区建国路88号",
      });
    }

    return data;
  };

  // 将clientData改为状态，以便能够更新数据
  const [clientData, setClientData] = useState<ClientData[]>(
    generateClientData()
  );

  // 分页数据
  const paginatedData = clientData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  // 表格列定义
  const columns = [
    {
      title: "客户编码",
      dataIndex: "clientCode",
      key: "clientCode",
      width: 100,
    },
    {
      title: "客户",
      dataIndex: "clientName",
      key: "clientName",
      width: 100,
    },
    {
      title: "行业",
      dataIndex: "industry",
      key: "industry",
      width: 80,
    },
    {
      title: "客户分类",
      dataIndex: "classification",
      key: "classification",
      width: 100,
    },
    {
      title: "联系人",
      dataIndex: "contactPerson",
      key: "contactPerson",
      width: 80,
    },
    {
      title: "联系电话",
      dataIndex: "contactPhone",
      key: "contactPhone",
      width: 120,
    },
    {
      title: "电子邮箱",
      dataIndex: "email",
      key: "email",
      width: 150,
    },
    {
      title: "销售部门",
      dataIndex: "department",
      key: "department",
      width: 100,
    },
    {
      title: "负责人",
      dataIndex: "responsiblePerson",
      key: "responsiblePerson",
      width: 80,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 60,
      render: (status: string) => (
        <span style={{ color: status === "启用" ? "#52c41a" : "#d9d9d9" }}>
          {status}
        </span>
      ),
    },
    {
      title: "客户地址",
      dataIndex: "address",
      key: "address",
      width: 180,
    },
    {
      title: "操作",
      key: "action",
      width: 100,
      render: (_:any, record: ClientData) => (
        <Space size="middle">
          <a className="edit-link" onClick={() => handleEdit(record)}>
            编辑
          </a>
          <a className="delete-link" onClick={() => handleDelete(record)}>
            删除
          </a>
        </Space>
      ),
    },
  ];

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 处理编辑操作
  const handleEdit = (record?: ClientData) => {
    setIsEdit(true);
    setIsModalVisible(true);
    
    // 如果有传入具体记录，则使用该记录
    if (record) {
      setTimeout(() => {
        setCurrentEditData(record);
      }, 0);
    }
    // 否则尝试使用选中行的数据
    else if (selectedRowKeys.length > 0) {
      const editData = clientData.find(
        (item) => item.key === selectedRowKeys[0]
      );
      if (editData) {
        setTimeout(() => {
          setCurrentEditData(editData);
        }, 0);
      }
    }
  };

  // 处理删除操作
  const handleDelete = (record?: ClientData) => {
    // 如果有传入具体记录，则使用该记录
    if (record) {
      Modal.confirm({
        title: "确认删除",
        content: `确定要删除客户「${record.clientName}」吗？`,
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          // 删除逻辑
          setClientData((prevData) => prevData.filter(item => item.key !== record.key));
        },
      });
    }
    // 否则尝试使用选中行的数据
    else if (selectedRowKeys.length > 0) {
      const deleteData = clientData.find(
        (item) => item.key === selectedRowKeys[0]
      );
      if (deleteData) {
        Modal.confirm({
          title: "确认删除",
          content: `确定要删除客户「${deleteData.clientName}」吗？`,
          okText: "确定",
          cancelText: "取消",
          onOk: () => {
            // 删除逻辑
            setClientData((prevData) => prevData.filter(item => item.key !== deleteData.key));
            setSelectedRowKeys([]);
          },
        });
      }
    }
  };

  // 处理新增操作
  const handleAdd = () => {
    console.log("新增客户");

    setIsEdit(false);
    setCurrentEditData(undefined);
    setIsModalVisible(true);
  };

  // 处理表单提交
  const handleSubmit = (values: ClientData) => {
    console.log("表单值:", values);

    if (isEdit && currentEditData?.key) {
      // 编辑模式：更新现有数据
      setClientData((prevData) =>
        prevData.map((item) =>
          item.key === currentEditData.key
            ? { ...values, key: currentEditData.key }
            : item
        )
      );
    } else {
      // 新增模式：添加新数据
      const newKey = (clientData.length + 1).toString();
      setClientData((prevData) => [...prevData, { ...values, key: newKey }]);
    }

    // 重置状态
    setIsModalVisible(false);
    setIsEdit(false);
    setCurrentEditData(undefined);
  };

  return (
    <div className="client-management">
      <div className="client-content">
        {/* 搜索筛选区域 */}
        <div className="search-filter">
          <Row gutter={16} align="middle">
            <Col span={5}>
              <Input placeholder="请输入客户名称/编号" />
            </Col>
            <Col>
              <Select placeholder="请选择状态">
                <Option value="启用">启用</Option>
                <Option value="禁用">禁用</Option>
              </Select>
            </Col>
            <Col>
              <Select placeholder="所属行业">
                <Option value="零售">零售</Option>
                <Option value="制造">制造</Option>
                <Option value="医药">医药</Option>
                <Option value="工程">工程</Option>
                <Option value="其他">其他</Option>
              </Select>
            </Col>
            <Col span={5}>
              <Input placeholder="负责人" />
            </Col>
            <Col span={4}>
              <Space>
                <Button className="reset-button">重置</Button>
                <Button type="primary" className="search-button">
                  查询
                </Button>
                <Button className="advanced-search-button">高级搜索</Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 操作按钮区域 */}
        <div className="action-buttons">
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length === 0}>
              删除
            </Button>
            <Button icon={<CopyOutlined />}>复制</Button>
            <Button icon={<ExportOutlined />}>导出</Button>
            <Button icon={<ImportOutlined />}>导入</Button>
            <Button icon={<ReloadOutlined />}>刷新</Button>
          </Space>
        </div>

        {/* 客户列表表格 */}
        <div className="client-table">
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={paginatedData}
            pagination={false}
            scroll={{
              x: "max-content",
              y: 400, // 设置表格内容区域的高度，超出时显示垂直滚动条
            }}
          />
        </div>

        {/* 分页区域 */}
        <div className="pagination">
          <div className="total-count">总 100 条</div>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={clientData.length}
            onChange={(page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `总 ${total} 条`}
            pageSizeOptions={["10", "20", "50", "100"]}
          />
        </div>

        {/* 编辑/新增弹窗 */}
        <ClientModal
          visible={isModalVisible}
          isEdit={isEdit}
          initialValues={currentEditData}
          onCancel={() => {
            setIsModalVisible(false);
            setIsEdit(false);
          }}
          onSubmit={handleSubmit}
        />
      </div>
    </div>
  );
}
